<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      modal-class="yyx-dialog"
      append-to-body
      :show-close="false"
      title="反馈/建议"
      width="500"
      :before-close="close"
    >
      <div class="content">
        <p>我们在哪些方面还能做的更好？</p>
        <span class="f12">我们的研发团队正在努力改善系统体验，如有建议，请点击反馈建议告知我们。</span>
        <p class="mt20">请告知我们这个问题</p>
        <span class="tips f12 mb16">创意好点子悬赏被采纳返积分，欢迎设计师们反馈</span>

        <!-- 商品分类 -->
        <el-select class="mb16" v-model="categoryValue" placeholder="寻找商品" style="width: 100%" @change="fileterFeedbackItem">
          <el-option v-for="item in feedbackCategory" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>

        <!-- 反馈项列表 -->
        <el-select class="mb16" v-model="itemValue" placeholder="请选择一个原因" :disabled="!categoryValue" style="width: 100%">
          <el-option v-for="item in feedbackItem" :key="item.itemId" :label="item.itemName" :value="item.itemId" />
        </el-select>

        <!-- 文本域，告知细节 -->
        <el-input
          class="dart-textarea mb16"
          v-model="textarea"
          style="width: 100%"
          :rows="4"
          type="textarea"
          placeholder="请告知我们更多细节，以便于我们更好的了解该问题"
        />

        <!-- 邮箱 -->
        <el-input class="mb16" v-model="email" style="width: 100%" placeholder="请输入邮箱" />

        <!-- 上传图片 -->
        <el-upload
          class="upload-demo upload-card"
          v-model:file-list="imgFileList"
          ref="uploadImg"
          :show-file-list="true"
          multiple
          list-type="picture-card"
          :auto-upload="false"
          :on-change="
            (file, fileList) => {
              handleAvatarChangeIcon(file, fileList);
            }
          "
        >
          <div style="display: flex; flex-direction: column; align-items: center; color: #86909c">
            <el-icon class="f24"><Plus /></el-icon>
            <p class="f12" style="line-height: 22px; color: #86909c">点击上传</p>
          </div>

          <template #file="{ file }">
            <div style="width: 100%">
              <img v-show="file.img" class="el-upload-list__item-thumbnail" :src="file.img" alt="" />
              <span
                v-show="!file.img"
                class="f30"
                style="display: flex; align-items: center; justify-content: center; width: 100%; height: 100%"
              >
                <el-icon><Loading /></el-icon>
              </span>
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="yyx-btn" @click="close">取消</el-button>
          <el-button class="yyx-btn" type="primary" @click="feedbackCommitFun"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { getFeedbackCategory, getFeedbackItem, imgsUpload, feedbackCommit } from "@/apis/feedback";

const dialogVisible = ref(false);
const feedbackCategory = ref([]);
const feedbackItem = ref([]);
const FeedbackItem = ref([]); //备份，避免前端过滤数据之后覆盖问题
const categoryValue = ref(""); //反馈分类值
const itemValue = ref(""); //反馈项值
const textarea = ref(""); //反馈细节，文本域
const email = ref(""); //邮箱
const imgFileList = ref([]); //编辑时商品图片list

const emit = defineEmits(["close"]);
const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isShow: false
      };
    }
  }
});

watch(
  () => props.optionInfo,
  val => {
    // console.log("反馈意见变化了");
    if (val) {
      dialogVisible.value = val.isShow;
    }
  },
  { deep: true }
);

onMounted(() => {
  getFeedbackCategoryFun();
  getFeedbackItemFun();
});

//过滤原因
const fileterFeedbackItem = clsId => {
  itemValue.value = "";
  const arr = FeedbackItem.value.filter(item => item.clsId === clsId);
  feedbackItem.value = arr;
};
// 获取反馈分类列表
const getFeedbackCategoryFun = () => {
  getFeedbackCategory().then(res => {
    if (res.code === 200) {
      feedbackCategory.value = res.data;
      console.log("分类列表===", feedbackCategory.value);
    }
  });
};
//获取反馈项列表
const getFeedbackItemFun = () => {
  getFeedbackItem().then(res => {
    if (res.code === 200) {
      feedbackItem.value = res.data;
      FeedbackItem.value = res.data;
      console.log("反馈项列表===", feedbackItem.value);
    }
  });
};

const feedbackCommitFun = _throttle(() => {
  const imgUrls = FileList.value?.map(item => item.img) || [];
  const imgIds = FileList.value?.map(item => item.uid) || [];
  const params = {
    itemId: itemValue.value, //反馈项id
    userEmail: email.value, //邮箱
    question: textarea.value, //反馈问题详细内容
    imgUrls: imgUrls.join(","),
    imgIds: imgIds.join(",")
  };

  feedbackCommit(params).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "意见反馈提交成功",
        type: "success",
        offset: 60
      });
      close();
    }
  });
}, 2000);

const close = () => {
  categoryValue.value = ""; //反馈分类值
  itemValue.value = ""; //反馈项值
  textarea.value = ""; //反馈细节，文本域
  email.value = ""; //邮箱
  imgFileList.value = []; //编辑时商品图片list
  emit("close");
};

//====================================图片上传========================================================================================
import { ElMessage } from "element-plus";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import {
  getFolder,
  _throttle, //节流，多次频繁触发时，只执行第一次
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";

const uploadImg = ref();
const FileList = ref([]);
// const imgIsReady = ref(false);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  const _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  //   imgIsReady.value = false;

  const flag = fileType(type, _fileList, type);

  if (!flag) {
    const errorFile = [];
    const successFile = [];
    if (type === "img") {
      ElMessage({
        message: "只能上传图片文件",
        type: "error",
        offset: 60
      });

      for (let item of _fileList) {
        if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }
    if (successFile.length <= 0) return;
  }
  if (type === "img") {
    FileList.value = fileList;
  }
  for (let item of _fileList) {
    await customUpload(item, { file: item }, type);
  }
}, 100);

/**
 * 校验文件类型
 */
const fileType = (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      if (!(item.raw.type === "video/mp4")) {
        flag = false;
      }
    }
  }
  return flag;
};
/**
 * 上传
 */
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  const folder = getFolder();
  const objName = folder + option.file.name;
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl);
      if (type === "img") {
        item["img"] = res.fileUrl.split("?")[0];
      }
      item["folder"] = objName;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const handleRemove = file => {
  console.log("移除===", file);
  uploadImg.value.handleRemove(file);
};

//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: option.file.folder, //目录＋文件名称
      url: option.file.img || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss">
.yyx-dialog {
  .dialog-footer {
    text-align: center;
  }
}
</style>
<style lang="scss" scoped>
:deep(.el-dialog) {
  color: red;
  text-align: center;
}
:deep(.el-textarea.dart-textarea) {
  .el-textarea__inner {
    background: #f2f3f5;
  }
}
p {
  padding: 0;
  margin: 0;
}
.content {
  p {
    color: #3d3d3d;
    line-height: 24px;
    margin-bottom: 4px;
    font-size: 14px;
  }
  .tips {
    display: block;
    padding: 0 24px;
    background-color: #d2f1de;
    border-radius: 16px;
    line-height: 32px;
    color: #4e5969;
  }
}
</style>
